from django.shortcuts import render, redirect
from webapp.modelforms.mymodelform import LoginForm
from webapp.models import Admin
from webapp.uitls.captchauitls import creat_captcha


def login(request):
    # 保存验证码
    def save_captcha():
        captcha_txt = creat_captcha(5, "webapp/static/img/captcha.png")
        request.session["captcha"] = captcha_txt

    if request.method == 'GET':
        save_captcha()
        form = LoginForm()
        return render(request, 'login.html', {"form": form})

    form = LoginForm(data=request.POST)
    # 要调用is_valid后，form.cleaned_data才有值，同理add——error也是要调用is_valid才可调用
    if form.is_valid():
        captcha = form.cleaned_data.get("captcha")
        session_captcha = request.session.get('captcha')
        if session_captcha.lower() != str(captcha).lower():
            msg = "验证码错误"
            form.add_error(error="验证码不正确", field='captcha')
            # 刷新验证码
            save_captcha()
            return render(request, 'login.html', {"form": form})
        # 查询条件去掉验证码
        form.cleaned_data.pop("captcha")
        admin = Admin.objects.filter(**form.cleaned_data).first()
        if admin:
            # 如果查询结果不为空，则认为登录登录成功
            # 生成session，并存储
            request.session['info'] = {"username": admin.username}
            # 重定向到部门管理页面
            return redirect('/depart/list/')
        form.add_error(error="用户名或密码不正确", field='password')
    save_captcha()
    return render(request, 'login.html', {"form": form})


def logout(request):
    # 清除当前用户session
    request.session.clear()
    # 退出登陆后，重定向到登录页面
    return redirect('/login/')
